<template>
  <el-dialog
    :title="$t('message.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="close"
  >
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in allList" :key="item.id" :label="item.id">{{
        item.title
      }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="close">{{ $t('message.universal.cancel') }}</el-button>
      <el-button @click="confirm" type="primary">
        {{ $t('message.universal.confirm') }}
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue'
import { roleList } from '@/api/role'
import { getUseRole, updatRole } from '@/api/user-manage'
import { watchLangChange } from '@/utils/i18n'
import { ElMessage } from 'element-plus'
// const show = ref(false)
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String
  }
})

const emits = defineEmits(['update:modelValue', 'updated'])
const confirm = async () => {
  await updateUserRole()
  ElMessage.success('更新成功')
  close()
  emits('updated')
}
const close = () => {
  emits('update:modelValue', false)
}
// 获取所有角色列表
const allList = ref([])
const getRoles = async () => {
  const resp = await roleList()
  allList.value = resp
}
getRoles()
watchLangChange(getRoles)
const checkList = ref([])
watch(
  () => props.roleId,
  async (val) => {
    if (!val) return
    checkList.value = []
    const resp = await getUseRole(props.roleId)
    checkList.value = resp.role.map((item) => item.id)
  }
)
// 更新用户角色
const updateUserRole = async () => {
  const data = allList.value.filter((it) => {
    return checkList.value.includes(it.id)
  })
  await updatRole(props.roleId, data)
}
</script>
<style less="scss"></style>
